package com.taoyibao.hongcanting.ui.mine.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.content.FileProvider;
import android.view.View;

import com.taoyibao.hongcanting.R;
import com.taoyibao.hongcanting.base.activity.BaseActivityPresenter;
import com.taoyibao.hongcanting.cache.SpUtils;
import com.taoyibao.hongcanting.constant.CodeConstant;
import com.taoyibao.hongcanting.constant.NetCode;
import com.taoyibao.hongcanting.dialog.DialogCamera;
import com.taoyibao.hongcanting.http.DefaultTransformer;
import com.taoyibao.hongcanting.http.JsonApiWrapper;
import com.taoyibao.hongcanting.http.ProgressSubscriber;
import com.taoyibao.hongcanting.model.CompanyBaseModel;
import com.taoyibao.hongcanting.model.UserInfoModel;
import com.taoyibao.hongcanting.ui.mine.delegate.VerifiedDelegate;
import com.taoyibao.hongcanting.utils.CameraUtils;
import com.taoyibao.hongcanting.utils.CodeUtils;
import com.taoyibao.hongcanting.utils.FileUtils;
import com.taoyibao.hongcanting.utils.ToastUtils;
import com.taoyibao.hongcanting.utils.permission.MPermission;
import com.taoyibao.hongcanting.utils.permission.OnMPermissionDenied;
import com.taoyibao.hongcanting.utils.permission.OnMPermissionGranted;
import com.taoyibao.hongcanting.utils.permission.OnMPermissionNeverAskAgain;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * @author TangAnna
 * @description: 实名认证
 * @date :${DATA} 13:21
 */
public class VerifiedActivity extends BaseActivityPresenter<VerifiedDelegate> implements View.OnClickListener, DialogCamera.DialogCameraInterface {

    /**
     * 0:正面 1：反面 2：手持身份证
     */
    private int mPosition;//点击的是哪一个图片
    //相册
    private static final int REQUEST_CODE_HEAD_ALBUM = 100;
    //相机
    private static final int REQUEST_CODE_HEAD_CAMERA = 101;
    //裁剪
    private static final int REQUEST_CODE_HEAD_CROP = 103;

    //请求权限
    private static final int REQUEST_CODE_PERMISSION = 102;

    //需要申请的权限的数组
    private String[] mPermissions = {Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    //用户选择的选择头像的方式
    private static final int WAY_CAMREA = 0;
    private static final int WAY_ALBUM = 1;
    /**
     * 方式 0相机  1相册
     */
    private int mWay = -1;
    private File mTempFile;
    private CameraUtils mCameraUtils;
    //图片文件
    private File mFileZheng;
    private File mFileFan;
    private File mFilePerson;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        viewDelegate.setFragmentManager(getSupportFragmentManager());
        super.onCreate(savedInstanceState);
    }

    @Override
    protected Class<VerifiedDelegate> getDelegateClass() {
        return VerifiedDelegate.class;
    }

    public static void open(Context context) {
        Intent intent = new Intent(context, VerifiedActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void bindEvenListener() {
        super.bindEvenListener();
        viewDelegate.get(R.id.btn_verified_confirm).setOnClickListener(this);
        viewDelegate.get(R.id.iv_verified_idCardZheng).setOnClickListener(this);
        viewDelegate.get(R.id.iv_verified_idCardFan).setOnClickListener(this);
        viewDelegate.get(R.id.iv_verified_person).setOnClickListener(this);
        getVerifiedInfo();
        mCameraUtils = new CameraUtils(this);
    }

    /**
     * 获取实名认证信息
     */
    public void getVerifiedInfo() {
        JsonApiWrapper.getApiService().userInfo(SpUtils.getToken(), SpUtils.getMemberId())
                .compose(new DefaultTransformer<CompanyBaseModel<List<UserInfoModel>>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<List<UserInfoModel>>>(this, true) {
                    @Override
                    public void onNext(CompanyBaseModel<List<UserInfoModel>> result) {
                        if (result.code == NetCode.HTTP_200 && result.data != null && result.data.size() > 0) {
                            viewDelegate.setData(result.data.get(0));
                        } else {
                            viewDelegate.setErrorView(new Throwable());
                            super.onNext(result);
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_verified_confirm://确认
                if (viewDelegate.canUpData()) {
                    upData();
                }
                break;
            case R.id.iv_verified_idCardZheng://正面
                mPosition = 0;
                showDialog();
                break;
            case R.id.iv_verified_idCardFan://反面
                mPosition = 1;
                showDialog();
                break;
            case R.id.iv_verified_person://手持
                mPosition = 2;
                showDialog();
                break;
        }
    }

    public void showDialog() {
        DialogCamera dialogCamera = new DialogCamera(this);
        dialogCamera.show(getSupportFragmentManager(), "TAG");
    }

    /**
     * 上传服务器数据
     */
    private void upData() {
        JsonApiWrapper.getApiService().userVerify(setParams(), getPhoto(mFileZheng, "id_front_photo"),
                getPhoto(mFileFan, "id_back_photo"), getPhoto(mFilePerson, "id_people_photo"))
                .compose(new DefaultTransformer<CompanyBaseModel>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel>(this, true) {
                    @Override
                    public void onNext(CompanyBaseModel companyBaseModel) {
                        if (companyBaseModel.code == 200) {
                            ToastUtils.showToast("提交成功");
                            FileUtils.deleteTempFile();
                            finish();
                        } else {
                            super.onNext(companyBaseModel);
                        }
                    }
                });
    }

    /**
     * 获取图片的Body
     *
     * @param file
     * @param name
     * @return
     */
    public MultipartBody.Part getPhoto(File file, String name) {
        RequestBody photoRequestBody = RequestBody.create(MediaType.parse(MultipartBody.FORM.toString()), file);
        MultipartBody.Part photoBody = MultipartBody.Part.createFormData(name, file.getName(), photoRequestBody);
        return photoBody;
    }

    /**
     * memberId 	是 	string 	会员id
     * user_name 	是 	string 	姓名
     * gender 	是 	int 	性别，只接受，1=>男,2=>女
     * nation 	是 	string 	民族
     * birth_date 	是 	int 	出身年月，时间戳
     * residence 	是 	string 	居住地址
     * id_no 	是 	string 	身份证号码
     *
     * @return
     */
    private HashMap<String, RequestBody> setParams() {
        HashMap<String, RequestBody> map = new HashMap<>();
        map.put("token", toRequestBody(SpUtils.getToken()));
        map.put("memberId", toRequestBody(SpUtils.getMemberId()));
        map.put("user_name", toRequestBody(viewDelegate.getName()));
        map.put("gender", toRequestBody(viewDelegate.getGrnder()));
        map.put("nation", toRequestBody(viewDelegate.getEthnic()));
        map.put("birth_date", toRequestBody(viewDelegate.getLongBirthday()));
        map.put("residence", toRequestBody(viewDelegate.getAddress()));
        map.put("id_no", toRequestBody(viewDelegate.getIDCard()));
        return map;
    }

    private RequestBody toRequestBody(String value) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), value);
        return requestBody;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    /**
     * 基本权限管理
     */
    private void requestBasicPermission(String[] permission, int requestCode) {
        MPermission.with(this)
                .addRequestCode(requestCode)
                .permissions(
                        permission
                ).request();
    }

    //同意
    @RequiresApi(api = Build.VERSION_CODES.M)
    @OnMPermissionGranted(REQUEST_CODE_PERMISSION)
    public void onBasicPermissionSuccess() {
        if (mWay == WAY_CAMREA) {//打开相机
            mCameraUtils.openCamera(REQUEST_CODE_HEAD_CAMERA, mCameraUtils.DIRECTORY_PICTURE);
        } else if (mWay == WAY_ALBUM) {//打开相册
            mCameraUtils.openAlbum(REQUEST_CODE_HEAD_ALBUM);
        }
    }

    //拒绝
    @OnMPermissionDenied(REQUEST_CODE_PERMISSION)
    public void onBasicPermissionFailed() {
        ToastUtils.showToast(CodeUtils.getIdString(R.string.string_hintPermission));
    }

    //不再提醒
    @OnMPermissionNeverAskAgain(REQUEST_CODE_PERMISSION)
    public void onBasicPermissionNeverAskAgain() {
        ToastUtils.showToast(CodeUtils.getIdString(R.string.string_hintPermission));
    }

    /**
     * 打开相机
     */
    private void openCamera() {
        mTempFile = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        //判断文件是否存在
        if (!mTempFile.getParentFile().exists()) {
            mTempFile.getParentFile().mkdirs();
        }
        // 通过FileProvider创建一个content类型的Uri
        Uri uri = FileProvider.getUriForFile(this, CodeConstant.PROVIDER_STR, mTempFile);
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE); //设置Action为拍照
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); //将拍取的照片保存到指定URI
        startActivityForResult(intent, REQUEST_CODE_HEAD_CAMERA);

    }

    /**
     * 打开相册
     */
    private void openAlbum() {
        Intent albumIntent = new Intent(Intent.ACTION_PICK);
        albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(albumIntent, REQUEST_CODE_HEAD_ALBUM);
    }

    /**
     * 相机
     */
    @Override
    public void onCameraListener() {
        mWay = WAY_CAMREA;
        requestBasicPermission(mPermissions, REQUEST_CODE_PERMISSION);
    }

    /**
     * 相册
     */
    @Override
    public void onAlbumListener() {
        mWay = WAY_ALBUM;
        requestBasicPermission(mPermissions, REQUEST_CODE_PERMISSION);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_HEAD_ALBUM://相册
                    Uri uri = data.getData();
                    mCameraUtils.openCrop(REQUEST_CODE_HEAD_CROP, CameraUtils.DIRECTORY_PICTURE, uri, 8, 5, 800, 500);
                    break;
                case REQUEST_CODE_HEAD_CAMERA://相机
                    mCameraUtils.openCrop(REQUEST_CODE_HEAD_CROP, CameraUtils.DIRECTORY_PICTURE, mCameraUtils.getOriginalUri(), 8, 5, 336, 240);
                    break;
                case REQUEST_CODE_HEAD_CROP://裁剪
                    Uri cropUri = mCameraUtils.getCropUri();
                    //设置图片
                    if (cropUri != null) {
                        switch (mPosition) {
                            case 0:
                                mFileZheng = mCameraUtils.getCropFile();
                                viewDelegate.setPhoneZheng(cropUri);
                                break;
                            case 1:
                                mFileFan = mCameraUtils.getCropFile();
                                viewDelegate.setPhoneFan(cropUri);
                                break;
                            case 2:
                                mFilePerson = mCameraUtils.getCropFile();
                                viewDelegate.setPhonePerson(cropUri);
                                break;
                        }
                    }
                    break;
            }
        }
    }
}
